#ifdef LT8920_TEST
#include <SPI.h>
#include "LT8920.h"

const uint8_t PIN_NRF_RST = 16;
const uint8_t PIN_NRF_CS = 5;
const uint8_t PIN_NRF_PKT = 4;
const uint8_t PIN_ROLE = 0;
bool writer;
SPIClass spi;
LT8920 lt(spi, PB12, PC7, PC6);
uint8_t buf[128];
int inx = 1;
void setup()
{
  Serial3.begin(9600);

  pinMode(PIN_ROLE, INPUT_PULLUP);

  delay(500);

  lt.begin();
  // lt.setCurrentControl(4, 15);
  lt.setDataRate(LT8920::LT8920_62KBPS);
  lt.setChannel(63);

  char sbuf[32];
  for (int i = 0; i < 128; i++)
    buf[i] = i;
  //verify chip registers.
  for (int i = 0; i <= 50; i++)
  {
    uint16_t value = lt.readRegister(i);

    sprintf_P(sbuf, PSTR("%d = %04x\r\n"), i, value);
    Serial3.print(sbuf);
  }

  if ((digitalRead(PIN_ROLE) == LOW))
  {
    writer = true;
    Serial3.println(F("Writer mode"));
  }
  else
  {
    writer = false;
    Serial3.println(F("Reader mode"));
    lt.startListening();
  }

  lt.whatsUp(Serial3);
  Serial3.println(F("Boot completed."));
}
int last;
void loop()
{

  if (writer)
  {
    delay(200);

    //send a packet.
    // uint8_t data[] = {1, 2, 3, 4, 5};

    lt.sendPacket(buf, inx);
    // lt.whatsUp(Serial3);
    Serial3.print("send:");
    Serial3.println(inx);
    writer = 0;
    last = millis();
  }
  else
  {
    if (lt.available())
    {
      Serial3.println(F("Data available"));

      uint8_t lbuf[256];
      for (int i = 0; i < 256; i++)
        lbuf[i] = 0;
      int packetSize = lt.read(lbuf, 256);
      if (packetSize > 0)
      {
        Serial3.println(F("Packet read OK"));

        //dump the packet.
        for (int i = 0; i < packetSize; i++)
        {
          Serial3.print(i);
          Serial3.print("=");
          Serial3.println(buf[i]);
        }
        if (inx < 63)
          inx += 1;
        writer = 1;
      }
      else
      {
        Serial3.println(F("Packet read fail"));
        lt.whatsUp(Serial3);
      }

      lt.startListening();
    }
    if (millis() - last > 10000)
      writer = 1;
  }
}
#endif